'use strict'

let models = require('../models');
let menus = require('../../config/menus');
let counter = require('../services/report')

let AttendanceStatus = models.AttendanceStatus;
let Attendance = models.Attendance;
let AttendanceReportCache = models.AttendanceReportCache;

let SchoolDao = models.SchoolDao;
let NatureClassDao = models.NatureClassDao;
let AttendanceReportCacheDao = models.AttendanceReportCacheDao;

let schoolService = require('../services/school');
let teacherService = require('../services/teacher');
let reportService = require('../services/report');
let absenceApplyService = require('../services/absenceapply');
let attendanceService = require('../services/attendance');
let trackService = require('../services/track');
let lib = {
    util: require('../lib/util'),
    menus: require('../lib/menus')
};

//Add viewIndex
let viewIndex = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);

        res.render('public/main', {
            basePath: '',
            title: '首页',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'index',
            selectedMenu: 'index',
            teacher: teacher,
            user: teacher
        });
    }
};

//Add viewHistoryAbsenceApply
let viewHistoryAbsenceApply = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let absenceApplies = {
            history: absenceApplyService.getAppliesOfTeacherBeforeToday(teacher),
        };

        res.render('public/main', {
            basePath: '',
            title: '历史假条',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'absence_apply',
            selectedMenu: 'history',
            teacher: teacher,
            user: teacher,
            absenceApplies: absenceApplies,
            lib: lib
        });
    }
};

//Add viewTodayAbsenceApply
let viewTodayAbsenceApply = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let absenceApplies = {
            today: absenceApplyService.getAppliesOfTeacherToday(teacher),
        };
        res.render('public/main', {
            basePath: '',
            title: '今日假条',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'absence_apply',
            selectedMenu: 'today',
            teacher: teacher,
            user: teacher,
            absenceApplies: absenceApplies,
            lib: lib
        });
    }
};

let viewTodayAttendance = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let school = teacherService.generateSchoolOfTeacher(teacher);

        school.statistics = attendanceService.emptyStatistics();
        school.peopleCount = 0;
        school.grades.forEach(function(grade){
            grade.statistics = attendanceService.emptyStatistics();
            grade.natureClasses.forEach(natureClass => {
                natureClass.statistics = attendanceService.getStatisticsOfNatureClassToday(natureClass)
                attendanceService.combineStatistics(grade.statistics, natureClass.statistics);
            });
            attendanceService.combineStatistics(school.statistics, grade.statistics);

            grade.peopleCount = grade.natureClasses.reduce((sum, natureClass) => {
                return sum + natureClass.students.length
            }, 0);
            school.peopleCount += grade.peopleCount;
        })

        res.render('public/main', {
            basePath: '',
            title: '当日考勤',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'attendance',
            selectedMenu: 'today',
            teacher: teacher,
            user: teacher,
            school: school,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

let viewDailyReport = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let school = teacherService.generateSchoolOfTeacher(teacher);

        school.statistics = attendanceService.emptyStatistics();
        school.peopleCount = 0;
        school.grades.forEach(function(grade){
            grade.statistics = attendanceService.emptyStatistics();
            grade.natureClasses.forEach(natureClass => {
                natureClass.statistics = attendanceService.getStatisticsOfNatureClassToday(natureClass)
                attendanceService.combineStatistics(grade.statistics, natureClass.statistics);
            });
            attendanceService.combineStatistics(school.statistics, grade.statistics);

            grade.peopleCount = grade.natureClasses.reduce((sum, natureClass) => {
                return sum + natureClass.students.length
            }, 0);
            school.peopleCount += grade.peopleCount;
        })

        res.render('public/main', {
            basePath: '',
            title: '当日考勤',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'attendance',
            selectedMenu: 'daily_report',
            teacher: teacher,
            user: teacher,
            school: school,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

//let findDailyReport = {
//    login: true,
//    privileges: [ 'teacher' ],
//    handler(req, res) {
//
//        let today = new Date();
//        today.setHours(0,0,0,0);
//
//        let user = req.session.login.user;
//        let teacher = teacherService.getTeacherByUserId(user.id);
//        let school = teacherService.generateSchoolOfTeacher(teacher);
//
//        school = SchoolDao.findOne({
//            id:school.id
//        });
//
//        let gradesInfo  = new Array();
//        school.grades.forEach(grade=>{
//            let natureClassesInfo = new Array();
//            grade.natureClasses.forEach(natureClass=>{
//                let classInfo = AttendanceReportCacheDao.findOne({
//                    date:date,
//                    natureClass:natureClass.id
//                });
//                let classAllInfo = {
//                    name:natureClass.name,
//                    classInfo:classInfo.toObject(plainAddendanceInfo())
//                };
//                natureClassesInfo.push(classAllInfo);
//            });
//            let gradeInfo = AttendanceReportCacheDao.findOne({
//                date:date,
//                grade:grade.id,
//                natureClass:null
//            });
//            let gradeAllInfo = {
//                name:grade.name,
//                gradeInfo:gradeInfo.toObject(plainAddendanceInfo()),
//                natureClassesInfo:natureClassesInfo
//            };
//            gradesInfo.push(gradeAllInfo);
//        });
//
//        let schoolInfo = AttendanceReportCacheDao.findOne({
//            date:date,
//            school:school.id,
//            grade:null,
//            natureClass:null
//        });
//
//        let schoolAllInfo = {
//            name: school.name,
//            schoolInfo: schoolInfo.toObject(plainAddendanceInfo()),
//            gradesInfo: gradesInfo
//        };
//
//        res.render('public/main', {
//            basePath: '',
//            title: '当日考勤',
//            menus: lib.menus.generateMenus(user),
//            role: 'teacher',
//            selectedTab: 'attendance',
//            selectedMenu: 'daily_report',
//            teacher: teacher,
//            user: teacher,
//            attendanceInfo: schoolAllInfo,
//            AttendanceDescriptions: models.AttendanceDescriptions
//        });
//    }
//};

//let findWeekOrMonthReport = {
//    login: true,
//    privileges: [ 'teacher' ],
//    handler(req, res) {
//        let user = req.session.login.user;
//        let teacher = teacherService.getTeacherByUserId(user.id);
//        let school = teacherService.generateSchoolOfTeacher(teacher);
//
//        school = SchoolDao.findOne({
//            id:school.id
//        });
//
//        let startTime = {};
//        let endTime = {};
//
//        let gradesInfo = new Array();
//        school.grades.forEach(grade=> {
//            let classesInfo = new Array();
//            grade.natureClasses.forEach(natureClass=> {
//                let classInfo = counter.countPeriodReport(startTime,endTime,2,natureClass);
//                let classAllInfo = {
//                    name:natureClass.name,
//                    classInfo:classInfo
//                };
//                classesInfo.push(classAllInfo);
//            });
//            let gradeInfo = counter.countPeriodReport(startTime,endTime,1,grade);
//            let gradeAllInfo = {
//                name:grade.name,
//                classesInfo:classesInfo,
//                gradeInfo:gradeInfo
//            };
//            gradesInfo.push(gradeAllInfo);
//        });
//        let schoolInfo = counter.countPeriodReport(startTime,endTime,0,school);
//        let schoolAllInfo = {
//            name:school.name,
//            schoolInfo:schoolInfo,
//            gradesInfo:gradesInfo
//        }
//
//        res.render('public/main', {
//            basePath: '',
//            title: '当日考勤',
//            menus: lib.menus.generateMenus(user),
//            role: 'teacher',
//            selectedTab: 'attendance',
//            selectedMenu: 'week_report',
//            teacher: teacher,
//            user: teacher,
//            attendanceInfo: schoolAllInfo,
//            AttendanceDescriptions: models.AttendanceDescriptions
//        });
//    }
//};

let viewWeekReport = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let school = teacherService.generateSchoolOfTeacher(teacher);

        school.statistics = attendanceService.emptyStatistics();
        school.peopleCount = 0;
        school.grades.forEach(function(grade){
            grade.statistics = attendanceService.emptyStatistics();
            grade.natureClasses.forEach(natureClass => {
                natureClass.statistics = attendanceService.getStatisticsOfNatureClassToday(natureClass)
                attendanceService.combineStatistics(grade.statistics, natureClass.statistics);
            });
            attendanceService.combineStatistics(school.statistics, grade.statistics);

            grade.peopleCount = grade.natureClasses.reduce((sum, natureClass) => {
                return sum + natureClass.students.length
            }, 0);
            school.peopleCount += grade.peopleCount;
        })

        res.render('public/main', {
            basePath: '',
            title: '当日考勤',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'attendance',
            selectedMenu: 'week_report',
            teacher: teacher,
            user: teacher,
            school: school,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

let viewMonthReport = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let school = teacherService.generateSchoolOfTeacher(teacher);

        school.statistics = attendanceService.emptyStatistics();
        school.peopleCount = 0;
        school.grades.forEach(function(grade){
            grade.statistics = attendanceService.emptyStatistics();
            grade.natureClasses.forEach(natureClass => {
                natureClass.statistics = attendanceService.getStatisticsOfNatureClassToday(natureClass)
                attendanceService.combineStatistics(grade.statistics, natureClass.statistics);
            });
            attendanceService.combineStatistics(school.statistics, grade.statistics);

            grade.peopleCount = grade.natureClasses.reduce((sum, natureClass) => {
                return sum + natureClass.students.length
            }, 0);
            school.peopleCount += grade.peopleCount;
        })

        res.render('public/main', {
            basePath: '',
            title: '当日考勤',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'attendance',
            selectedMenu: 'month_report',
            teacher: teacher,
            user: teacher,
            school: school,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

//let viewAttendanceReport = {
//    login: true,
//    privileges: [ 'teacher' ],
//    handler(req, res) {
//        let user = req.session.login.user;
//        let teacher = teacherService.getTeacherByUserId(user.id);
//        let school = teacherService.generateSchoolOfTeacher(teacher);
//
//        let queryPeriod = req.query.period;
//        let queryType = req.query.type;
//        let queryId = req.query.id;
//
//        let term = schoolService.getCurrentTerm(school);
//        if ( !term ) {
//            res.render('leader/attendance/report', {
//                basePath: '',
//                statisticsList: []
//            });
//
//            return;
//        }
//
//        let periods = [];
//        if ( queryPeriod == 'week' ) {
//            periods = reportService.generateWeeksInTerm(term);
//        }
//        else if ( queryPeriod == 'month' ) {
//            periods = reportService.generateMonthsInTerm(term);
//        }
//        else {
//            periods = reportService.generateDaysInTerm(term);
//        }
//
//        let renderContent = {
//            basePath: '',
//            lib: lib,
//            period: queryPeriod
//        };
//        if ( queryType == 'school' ) {
//            reportService.calcSchoolStatistics(school, periods);
//            renderContent.peopleCount = school.peopleCount;
//            renderContent.statisticsList = school.statisticsList;
//        }
//        else if ( queryType == 'grade' ) {
//            let grade = school.grades.find(grade => {
//                return grade.id == queryId
//            });
//
//            reportService.calcGradeStatistics(grade, periods);
//            renderContent.peopleCount = grade.peopleCount;
//            renderContent.statisticsList = grade.statisticsList;
//        }
//        else if ( queryType == 'class' ) {
//            let natureClass = NatureClassDao.findOne({
//                id: queryId
//            });
//
//            reportService.calcNatureClassStatistics(natureClass, periods);
//            renderContent.peopleCount = natureClass.peopleCount;
//            renderContent.statisticsList = natureClass.statisticsList;
//        }
//
//        res.render('teacher/attendance/report', renderContent);
//    }
//};

let viewAttendanceReport = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let school = teacherService.generateSchoolOfTeacher(teacher);

        let queryPeriod = req.query.period;
        let queryType = req.query.type;
        let queryId = req.query.id;


        let term = schoolService.getCurrentTerm(school);
        if ( !term ) {
            res.render('leader/attendance/report', {
                basePath: '',
                statisticsList: []
            });

            return;
        }

        let periods = [];
        if ( queryPeriod == 'week' ) {
            periods = reportService.generateWeeksInTerm(term);
        }
        else if ( queryPeriod == 'month' ) {
            periods = reportService.generateMonthsInTerm(term);
        }
        else {
            periods = reportService.generateDaysInTerm(term);
        }

        let renderContent = {
            basePath: '',
            lib: lib,
            period: queryPeriod
        };

        let attendanceScope = {
            'school':0,
            'grade':1,
            'class':2
        };

        let attendanceInfo = new Array();
        periods.forEach(period=>{
            let info = counter.countPeriodReport(period.startTime,period.endTime,attendanceScope[queryType],queryId);
            attendanceInfo.push({
                startTime:period.startTime,
                endTime:period.endTime,
                info:info.toObject({recursive:true})
            });
            console.log(period.endTime);
        });

        renderContent.statisticsList = attendanceInfo;

        //res.json({
        //    successful:true,
        //    info:attendanceInfo
        //});

        res.render('teacher/attendance/report', renderContent);
    }
};


let viewSearchAttendance = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
            
        let startTime = new Date(Number(req.query.start));
        let endTime = new Date(Number(req.query.end));
        let status = req.query.status;

        let now = new Date();
        if ( !req.query.start ) {
            startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, -1);
        }
        if ( !req.query.end ) {
            endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59);
        }
        if ( !status ) {
            status = 0;
        }

        console.log(startTime);
        console.log(endTime);
        let students = [];
        //if ( req.query.start && req.query.end ) {
        if ( !req.query.nature_class ) {
            students = lib.util.concatArrays(
                teacher.managedClasses.map(natureClass => natureClass.students));
        }
        else {
            console.log('filter by nature_class');
            students = teacher.managedClasses.find(natureClass => {
                return natureClass.id == req.query.nature_class
            }).students;
        }
        //}

        let sid = req.query.sid;
        if ( sid ) {
            students = students.filter(student => student.sid == sid);
        }

        let studentName = req.query.name;
        if ( studentName ) {
            students = students.filter(student => student.name == studentName);
        }

        students.forEach(student => {
            student.statistics = attendanceService.getStatisticsOfStudent(student, startTime, endTime)
        });

        students = attendanceService.filterStudentsByStatus(students, status);
        let absenceAppliesCount = absenceApplyService.getAppliesCountOfTeacher(teacher);

        res.render('public/main', {
            basePath: '',
            title: '考勤查询',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'attendance',
            selectedMenu: 'search',
            teacher: teacher,
            user: teacher,
            absenceAppliesCount: absenceAppliesCount,
            students: students
        });
    }
};

let viewManual = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        let absenceAppliesCount = absenceApplyService.getAppliesCountOfTeacher(teacher);
            
        if ( !req.query.date ) {
            req.query.date = Date.now();
        }

        // 创建时间筛选
        let date = new Date(Number(req.query.date));
        let startTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, -1);
        console.log(startTime);
        let endTime = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 24, -1);
        console.log(endTime);

        // 获取所有学生
        let natureClassId = req.query.nature_class;
        let students = null;
        if ( !natureClassId ) {
            students = lib.util.concatArrays(
                    teacher.managedClasses.map(natureClass => natureClass.students));
        }
        else {
            students = teacher.managedClasses.find(natureClass => {
                return natureClass.id == natureClassId;
            }).students;
        }
        console.log(students.length);

        // 获取学生编号
        let sid = req.query.sid;
        if ( sid ) {
            students = students.filter(student => student.sid == sid);
        }
        console.log(students.length);

        // 获取学生姓名
        let studentName = req.query.name;
        if ( studentName ) {
            students = students.filter(student => student.name == studentName);
        }
        console.log(students.length);

        let attendanceStatus = req.query.status;
        if ( !attendanceStatus || attendanceStatus == 'undefined' ) {
            attendanceStatus = AttendanceStatus.Created;
        }
        console.log(attendanceStatus);

        // 获取考勤信息列表
        let attendances = attendanceService.queryAttendancesOfStudents(
                students, startTime, endTime, attendanceStatus);
        console.log(attendances.length);

        res.render('public/main', {
            basePath: '',
            title: '考勤补录',
            menus: lib.menus.generateMenus(user),
            role: 'teacher',
            selectedTab: 'manual',
            selectedMenu: 'manual',
            teacher: teacher,
            user: teacher,
            students: students,
            attendances: attendances,
            attendanceObjects: Attendance.toObjectArray(attendances, {
                includes: [ {
                    values: [ 'enterStatus', 'exitStatus' ]
                } ]
            }),
            absenceAppliesCount: absenceAppliesCount,
            AttendanceDescriptions: models.AttendanceDescriptions
        });
    }
};

let actionDealAbsenceApply = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        let user = req.session.login.user;
        let teacher = teacherService.getTeacherByUserId(user.id);
        teacherService.updateAbseneceApply(teacher, req.body.apply);

        res.json({
            successful: true
        });
    }
};

let actionUpdateAttendances = {
    login: true,
    privileges: [ 'teacher' ],
    handler(req, res) {
        attendanceService.updateAttendanceValues(req.body.values);

        res.json({
            successful: true
        });
    }
}

function isErrorStatus(status) {
    return status == AttendanceStatus.Absent ||
        status == AttendanceStatus.Late ||
        status == AttendanceStatus.Early;
}

module.exports = {
    viewHistoryAbsenceApply,
    viewTodayAbsenceApply,
    viewSearchAttendance,
    viewDailyReport,
    viewWeekReport,
    viewMonthReport,
    viewAttendanceReport,
    viewIndex,
    viewManual,
    actionDealAbsenceApply,
    actionUpdateAttendances
};

function plainAttendanceInfo(){
    let plainInfo = {
        includes:[
            date,
            {
                personTimeInfo:[
                    attendCount,
                    leaveCount,
                    lateCount,
                    absenceCount,
                    earlyCount
                ]
            }
        ]
    };
    return plainInfo
}